<?php

namespace Core\init;

use Core\annotations\Bean;
use FastRoute\RouteCollector;
use function FastRoute\simpleDispatcher;

/**
 * Class RouterCollect
 * @package Core\init
 * @Bean()
 */
class RouterCollect
{
    public array $router = [];

    /**
     * 收集路由
     * @param $method
     * @param $uri
     * @param $handler
     */
    public function addRouter($method, $uri, $handler)
    {
        $this->router[] = array(
            'method' => $method,
            'uri' => $uri,
            'handler' => $handler,
        );
    }

    public function getDispatcher(): \FastRoute\Dispatcher
    {
        //实例化一个理由对象
        return simpleDispatcher(function (RouteCollector $r) {
            foreach ($this->router as $k => $router) {
                $r->addRoute($router['method'], $router['uri'], $router['handler']);
            }
        });
    }
}
